<?php

use Illuminate\Support\Facades\DB;

/**
 * json 输出
 * @param  integer $code [状态码]
 * @param  string  $msg    [说明]
 * @param  [type]  $data   [数据]
 * @param  [type]  $option [额外数据]
 * @return [type]          [json]
 */
function json($code=200,$msg='ok',$data=[],$option=[])
{
	$result = array_merge($data, $option);
	$result['code'] = (int)$code;
	$result['msg'] = (string)$msg;
	header("Content-Type:text/json; charset=utf-8");
    header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
    echo (json_encode($result, 256));
    return;
}

if(!function_exists('articleCount')){
    function articleCount($typeid = 0)
    {
        $re = DB::table('articles')->where('type_id', $typeid)->count();
        // $re = Redis::get('article_count:type_id'.$typeid);
        return $re;
    }
}

if(!function_exists('commentCount')){
    function commentCount($article_id = 0)
    {
        $re = DB::table('comments')->where('article_id', $article_id)->count();
        return $re;
    }
}

if(!function_exists("_toArray")){
    function _toArray($data){
        return json_decode(json_encode($data),512);
    }
}

if(!function_exists('_substr')){
    /**
     * 中文字符串截取
     * @param $str 要截取的内容
     * @param int $length 截取长度
     * @param string $encoding 编码
     * @return string
     */
    function _substr($str,$length=70,$encoding="utf-8")
    {
        $str = trim(strip_tags($str));
        $data = mb_substr($str,0,$length,$encoding);
        return $data;
    }
}

if(!function_exists('_articleTags')){
    /**
     * 获取文章tags
     * @param $id
     * @return string
     */
    function _articleTags($id){
        $re = _toArray(DB::select("SELECT * FROM blog_article_tags AS a LEFT JOIN blog_tags b ON a.`tag_id` = b.`id` WHERE a.article_id = {$id}"));
        return implode(",",array_column($re,"name"));
    }
}

if(!function_exists('_getImg')){
    function _getImg($str)
    {
        if(!empty($str)){
            // 获取图片标签
            preg_match_all('/<img.+>/', $str, $data);
            // 获取图片路径
            if(!empty($data[0][0])){
                preg_match_all('/src=("|\')(.*)\\1/Us', $data[0][0], $arr);
                // 返回图片路径
                return empty($arr[2][0]) ? "" : $arr[2][0];
            }
        }

    }
}